package com.huxiu.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.huxiu.APP;
import com.huxiu.DetailActivity;
import com.huxiu.HuaTiDetailActivity;
import com.huxiu.LogInActivity;
import com.huxiu.R;
import com.huxiu.ShareActivity;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

/**
 * Created by tian on 15/4/17:下午5:32.
 */
@SuppressWarnings({"unused", "SetJavaScriptEnabled"})
public class Utils {
    //qcl单例toast和主线程刷新ui
    private static Toast toast;

    /**
     * 在主线程中刷新UI的方法
     *
     * @param r
     */
    public static void runOnUIThread(Runnable r) {
        APP.getMainHandler().post(r);
    }

    public static void showToast(int resId) {
        // Toast.makeText(App.getInstance(), resId, Toast.LENGTH_SHORT).show();
        //qcl单例toast
        if (toast == null) {
            toast = Toast.makeText(APP.getInstance(), resId, Toast.LENGTH_SHORT);
        }
        toast.setText(resId);
        toast.setGravity(Gravity.CENTER, 0, 10);//设置toast显示位置
        toast.show();
    }

    public static void showToast(String msg) {
        //Toast.makeText(App.getInstance(), msg, Toast.LENGTH_SHORT).show();
        //qcl单例toast
        if (toast == null) {
            toast = Toast.makeText(APP.getInstance(), msg, Toast.LENGTH_SHORT);
        }
        toast.setText(msg);
        toast.setGravity(Gravity.CENTER, 0, 10);
        toast.show();
    }


    //dp转px
    public static int dip2px(float dpValue) {
        final float scale = APP.getInstance().getResources().getDisplayMetrics().density;
        return (int) ((dpValue * scale) + 0.5f);
    }


    public static String toHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String doubleBit = Integer.toHexString(b & 0xff);
            if (doubleBit.length() == 1) {
                hexString.append('0');
            }
            hexString.append(doubleBit);
        }
        return hexString.toString().toLowerCase();
    }

    public static String getEncryptedPassword(String password) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            byte[] data = password.getBytes();
            return toHexString(m.digest(data));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return password;
        }
    }

    public static void makeCall(Context context, String number) {
        if (TextUtils.isEmpty(number)) {
            return;
        }
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel",
                    number, null));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "该设备不支持拨打电话功能", Toast.LENGTH_LONG).show();
        }
    }

    public static void closeKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    //设置webview
    public static void setDefaultWebSettings(WebView webview) {
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        //        webview.getSettings().setUseWideViewPort(true);//可以任意缩放比例
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setLoadWithOverviewMode(true);
        //支持javascript
        webview.getSettings().setJavaScriptEnabled(true);

        webview.getSettings().setDomStorageEnabled(true);
        // 设置禁止缩放工具
        webview.getSettings().setBuiltInZoomControls(false);
        webview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

        //--------------从网上找到的webview功能---------------------------------
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webview.getSettings().setLoadsImagesAutomatically(true);  //支持自动加载图片
        // -----------------------------------------------
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }
        });
    }


    //显示时间
    private static final long SECOND_GAP = 10 * 1000;
    private static final int MINUTE_MILLI = 60 * 1000;

    public static boolean isInSameMinute(long sendTime, long now) {
        return now - sendTime < MINUTE_MILLI;
    }

    private static final int HOUR_MILLI = 60 * 60 * 1000;

    public static boolean isInSameHour(long sendTime, long now) {
        return now - sendTime < HOUR_MILLI;
    }

    private static final int DAY_MILLI = 24 * 60 * 60 * 1000;

    public static boolean isInSameDAY(long sendTime, long now) {
        return now - sendTime < DAY_MILLI;
    }

    private static final int WEEK_MILLI = 7 * 24 * 60 * 60 * 1000;

    public static boolean isInSameWeek(long sendTime, long now) {
        return now - sendTime < WEEK_MILLI;
    }

    public static String getDateString(long create_time) {
        Context context = APP.getInstance();
        long now = System.currentTimeMillis();
        long time = create_time * 1000;
        Log.e("time", "create_time" + create_time);
        Log.e("time", "now" + now);
        Log.e("time", "time" + time);
        if (now - time < SECOND_GAP) {
            return context.getString(R.string.just_now);
        } else if (isInSameMinute(time, now)) {
            return (now - time) / 1000 + "秒前";
        } else if (isInSameHour(time, now)) {
            return (now - time) / 60 / 1000 + "分钟前";
        } else if (isInSameDAY(time, now)) {
            return (now - time) / 60 / 60 / 1000 + "小时前";
        } else if (isInSameWeek(time, now)) {
            return (now - time) / 24 / 60 / 60 / 1000 + "天前";
        } else {
            Date date = new Date(create_time * 1000);
            return String.valueOf(DateFormat.format("yyyy-MM-dd", date));
        }
    }

    public static boolean isHuxiuArticleUrl(Uri uri) {
        try {
            String host = uri.getHost();
            if (host.endsWith(".huxiu.com")) {
                List<String> segments = uri.getPathSegments();
                if (segments.size() >= 2 && segments.get(0).contentEquals("article")) {
                    return true;
                }
            }
        } catch (Exception e) {
            //if NPE occurs, ignore it
        }
        return false;
    }


    public static Intent getArticleIntentFromUri(Activity activity, Uri uri) {
        String paramid = uri.getPathSegments().get(1);
        String id = paramid.replace(".html", "");
        Intent intent = new Intent(activity, DetailActivity.class);
        intent.putExtra(Constants.ARTICLE_ID_KEY, id);
        //        intent.putExtra(Constants.ARTICLE_URL_KEY, url);
        return intent;
    }

    public static boolean isHuxiuCommentUrl(Uri uri) {
        try {
            String host = uri.getHost();
            if (host.endsWith(".huxiu.com")) {
                List<String> segments = uri.getPathSegments();
                if (segments.size() >= 2 && segments.get(0).contentEquals("get_comment")) {
                    return true;
                }
            }
        } catch (Exception e) {
            //if NPE occurs, ignore it
        }
        return false;
    }


    //判断是否登录过，如果没有登录就跳转到登录界面
    public static void askLogIn(Activity activity) {
        Intent intent = new Intent(activity, LogInActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.activity_open, 0);
    }

    public static void push_to_huati(Context mContext, String id) {
        Intent intent = new Intent(mContext, HuaTiDetailActivity.class);
        intent.putExtra(Constants.PUSH_ID_KEY, id);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //        s_activity.startActivity(intent);
    }

    public static void push_to_article(Context mContext, String id) {
        Intent intent = new Intent(mContext, DetailActivity.class);
        intent.putExtra(Constants.PUSH_ID_KEY, id);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //        s_activity.startActivity(intent);
    }


    public static void launchShareActivity(Activity activity, String title, String url, String type,
                                           String imageUrl, String description, Bitmap image, int share_intent) {
        Intent intent = new Intent(activity, ShareActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        intent.putExtra("type", type);
        intent.putExtra(UmenEvent.SHARE_INTENT_KEY, share_intent);
        Bitmap bmp = ImageUtils.getWeChatShareBitmap(image);
        if (bmp != null)
            intent.putExtra("image", bmp);
        if (imageUrl != null)
            intent.putExtra("imageUrl", imageUrl);
        if (description != null)
            intent.putExtra("description", description);
        activity.startActivity(intent);
        //        activity.overridePendingTransition(R.anim.activity_open, 0);
    }


    public static void doCopy(String text) {
        ClipboardManager cm = (ClipboardManager) APP.getInstance()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText("", text));
    }


    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            String device_id = tm.getDeviceId();

            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);

            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }

            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
            }

            json.put("device_id", device_id);

            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String SubString(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        if (str.length() > 200) {
            return str.substring(0, 200);
        }
        return str;
    }


    //浏览量万以上显示万+
    public static String getSeeNumToStr(int num) {
        if (num >= 10000) {
            return "1万+";
        } else if (num >= 20000) {
            return "2万+";
        } else if (num >= 30000) {
            return "3万+";
        } else if (num >= 40000) {
            return "4万+";
        } else if (num >= 50000) {
            return "5万+";
        } else if (num >= 60000) {
            return "6万+";
        } else if (num >= 70000) {
            return "7万+";
        } else if (num >= 80000) {
            return "8万+";
        } else {
            return Integer.toString(num);
        }
    }


    public static String getVersionName(Context mContext) {
        try {
            String pkName = mContext.getPackageName();
            String versionName = mContext.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = mContext.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            return versionName;
        } catch (Exception e) {
        }
        return "";
    }


    public static String pkName(Context mContext) {
        String pkName = mContext.getPackageName();
        return pkName;
    }
}
